import { Divider, Modal, Row, Col, message, Card, Tree, Input, Popconfirm, Tooltip, Button } from 'antd';
import { connect, useRequest } from 'umi';
import React, { Component } from 'react';
import { PlusSquareOutlined, MinusSquareOutlined, FormOutlined, ArrowDownOutlined, ArrowUpOutlined, SearchOutlined } from '@ant-design/icons';
import { deletedepartment, editdepartment, adddepartment, departmember } from '@/services/basic';
import AutoTable from '@/components/AutoTable'

const { TreeNode } = Tree;
let col = { xs: 24, sm: 24, md: 10, lg: 9, xl: 8, xxl: 8 },
    cols = { xs: 24, sm: 24, md: 14, lg: 15, xl: 16, xxl: 16 };
const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.key === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};

function mapTree(org) {
    const haveChildren = Array.isArray(org.childrens) && org.childrens.length > 0;
    return {
        //分别将我们查询出来的值做出改变他的key
        num: org.num,
        title: org.name,
        key: org.id,
        //判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
        children: haveChildren ? org.childrens.map(i => mapTree(i)) : []
    };
}


@connect(({ global, loading }) => ({
    global,
    // submitting: loading.effects['global/globalqueryList'],
}))
class Department extends React.Component {
    state = {
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        treeData: [],
        dataSource: [],
        dataList: []
    };


    //设置新状态
    setNewState(type, values, fn) {
        const { dispatch } = this.props;
        dispatch({
            type: 'basic/' + type,
            payload: values
        }).then((res) => {
            if (res) {
                fn ? fn(res) : null;
            }
        });
    }



    resetData(fn) {
        this.setNewState("department", {}, (res) => {
            this.setState({
                treeData: res.data.length > 0 ? res.data.map(it => mapTree(it)) : []
            }, () => {
                fn ? fn() : null
            })
        })
    }

    componentDidMount() {
        this.resetData(() => {
            const { treeData } = this.state, dataList = [];
            const generateList = (data, list) => {
                for (let i = 0; i < data.length; i++) {
                    const node = data[i];
                    const { key } = node;
                    list.push({ key, title: node.title });
                    if (node.children) {
                        generateList(node.children, list);
                    }
                }
            };
            generateList(treeData, dataList);
            this.setState({
                expandedKeys: dataList.map(it => it.key),
                dataList
            })
        });
    }

    onExpand = expandedKeys => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };


    onChange = e => {
        const { value } = e.target;
        const { treeData } = this.state, dataList = [];
        const generateList = (data, list) => {
            for (let i = 0; i < data.length; i++) {
                const node = data[i];
                const { key } = node;
                list.push({ key, title: node.title });
                if (node.children) {
                    generateList(node.children, list);
                }
            }
        };
        generateList(treeData, dataList);
        const expandedKeys = dataList.map(item => {
            if (item.title.indexOf(value) > -1) {
                return getParentKey(item.key, treeData);
            }
            return null;
        }).filter((item, i, self) => item && self.indexOf(item) === i);
        let curkey = dataList.some(it => it.title.indexOf(value) > -1) && dataList.filter(it => it.title.indexOf(value) > -1)[0].key;
        if (expandedKeys.indexOf(curkey) == -1) {
            expandedKeys.push(curkey);
        }
        this.setState({
            expandedKeys,
            searchValue: value,
            autoExpandParent: true,
        });
    };




    render() {
        const { searchValue, expandedKeys, autoExpandParent, treeData } = this.state;
        const loop = data => data.map(item => {
            const index = item.title.indexOf(searchValue);
            const beforeStr = item.title.substr(0, index);
            const afterStr = item.title.substr(index + searchValue.length);
            const title =
                index > -1 ? (
                    <Tooltip title={item.title} placement="bottom">
                        <span style={{ display: "inline-block", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                            {beforeStr}
                            <span style={{ color: '#f50' }}>{searchValue}</span>
                            {afterStr}
                        </span>
                    </Tooltip>
                ) : (
                    <Tooltip title={item.title} placement="bottom">
                        <span style={{ display: "inline-block", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{item.title}</span>
                    </Tooltip>
                );

            const actiontitle = (
                <div style={{ display: "flex", alignItems: "center" }}>
                    {title}({item.num})
                    <Divider type='vertical'></Divider>
                    <Tooltip title="编辑" onClick={(e) => {
                        e.stopPropagation();
                        const _it = this;
                        this.setState({
                            savetitle: null
                        })
                        Modal.confirm({
                            icon: <></>,
                            closable: true,
                            title: "修改部门名称",
                            content: <div>
                                <Input allowClear onChange={(e) => {
                                    _it.setState({
                                        savetitle: e.target.value
                                    })
                                }}></Input>
                            </div>,
                            cancelText: "取消",
                            okText: "修改",
                            onOk: () => {
                                return new Promise((resolve, reject) => {
                                    if (_it.state.savetitle) {
                                        editdepartment({
                                            name: _it.state.savetitle,
                                            id: item.key,
                                        }).then(res => {
                                            if (res.code == 0) {
                                                _it.resetData()
                                            } else {
                                            }
                                        })
                                        resolve()
                                    } else {
                                        message.warn("请输入修改的名称")
                                        reject()
                                    }
                                })
                            }

                        })
                    }}>
                        <FormOutlined style={{ color: "#1890ff" }} />
                    </Tooltip>
                    <Divider type='vertical'></Divider>
                    <Tooltip title="新增">
                        <PlusSquareOutlined
                            onClick={(e) => {
                                e.stopPropagation();
                                const _it = this;
                                this.setState({
                                    savetitle: null
                                })
                                Modal.confirm({
                                    icon: <></>,
                                    closable: true,
                                    title: "新增子部门",
                                    content: <div>
                                        <Input allowClear onChange={(e) => {
                                            _it.setState({
                                                savetitle: e.target.value
                                            })
                                        }}></Input>
                                    </div>,
                                    cancelText: "取消",
                                    okText: "新增",
                                    onOk: () => {
                                        return new Promise((resolve, reject) => {
                                            if (_it.state.savetitle) {
                                                adddepartment({
                                                    name: _it.state.savetitle,
                                                    parent_department_id: item.key
                                                }).then(res => {
                                                    if (res.code == 0) {
                                                        _it.resetData()
                                                    } else {
                                                    }
                                                })
                                                resolve()
                                            } else {
                                                message.warn("请输入修改的名称")
                                                reject()
                                            }
                                        })
                                    }
                                })
                            }}
                            style={{ color: "green" }}
                        /></Tooltip>
                    {
                        (!item.children || item.children.length == 0) &&
                        <Divider type='vertical'></Divider>
                    }
                    {
                        (!item.children || item.children.length == 0) &&
                        <Popconfirm
                            placement='bottom'
                            title="是否删除该部门？"
                            okText="删除"
                            cancelText="取消"
                            onConfirm={() => {
                                deletedepartment(item.key).then(res => {
                                    this.resetData()
                                })
                            }}
                        >
                            <Tooltip title="删除">
                                <MinusSquareOutlined onClick={(e) => { e.stopPropagation() }} style={{ color: "red" }} />
                            </Tooltip>
                        </Popconfirm>
                    }
                </div>
            )

            if (item.children) {
                return (
                    <TreeNode key={item.key} title={actiontitle}>
                        {loop(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode key={item.key} title={title} />;
        });




        return (
            <Card title={this.props.route.name} bordered={false}>
                <Row gutter={12}>
                    <Col {...col} style={{ padding: "0 20px" }}>
                        <div style={{ display: "flex" }}>
                            <div style={{ overflow: "hidden", width: "100%", flexShrink: 0 }}>
                                <div style={{ paddingTop: 16 }}>
                                    <Input prefix={<SearchOutlined />} placeholder="搜索备件部门" onChange={this.onChange} style={{ flex: 1 }} />
                                </div>
                                <div style={{ margin: 0, padding: "16px 12px 12px 8px", display: "flex", justifyContent: "flex-start", alignItems: "center" }}>
                                    <span>全部部门</span>
                                    <a disabled={treeData.length > 0} style={{ marginLeft: 12, marginRight: 12 }} onClick={() => {
                                        if (treeData.length > 0) {
                                            return
                                        }
                                        const _it = this;
                                        this.setState({
                                            savetitle: null
                                        })
                                        Modal.confirm({
                                            icon: <></>,
                                            closable: true,
                                            title: "新增部门",
                                            content: <div>
                                                <Input allowClear onChange={(e) => {
                                                    _it.setState({
                                                        savetitle: e.target.value
                                                    })
                                                }}></Input>
                                            </div>,
                                            cancelText: "取消",
                                            okText: "新增",
                                            onOk: () => {
                                                return new Promise((resolve, reject) => {
                                                    if (_it.state.savetitle) {
                                                        adddepartment({
                                                            name: _it.state.savetitle,
                                                            parent_department_id: null
                                                        }).then(res => {
                                                            if (res.code == 0) {
                                                                _it.resetData()
                                                            } else {
                                                            }
                                                        })
                                                        resolve()
                                                    } else {
                                                        message.warn("请输入名称")
                                                        reject()
                                                    }
                                                })
                                            }
                                        })

                                    }}>添加</a>
                                    <div style={{ marginTop: 2, color: "#1890ff" }}>
                                        {
                                            expandedKeys.length > 0 ?
                                                <Tooltip title="收起全部">
                                                    <ArrowUpOutlined onClick={() => {
                                                        this.setState({
                                                            expandedKeys: []
                                                        })
                                                    }} />
                                                </Tooltip> :
                                                <Tooltip title="展开全部">
                                                    <ArrowDownOutlined onClick={() => {
                                                        const { treeData } = this.state, dataList = [];
                                                        const generateList = (data, list) => {
                                                            for (let i = 0; i < data.length; i++) {
                                                                const node = data[i];
                                                                const { key } = node;
                                                                list.push({ key, title: node.title });
                                                                if (node.children) {
                                                                    generateList(node.children, list);
                                                                }
                                                            }
                                                        };
                                                        generateList(treeData, dataList);
                                                        this.setState({
                                                            expandedKeys: dataList.map(it => it.key)
                                                        })
                                                    }} />
                                                </Tooltip>
                                        }
                                    </div>


                                </div>
                                <Tree
                                    onSelect={(selectedKeys, e) => {
                                        if (!selectedKeys[0]) {
                                            return
                                        }
                                        let curitem = this.state.dataList.filter(it => {
                                            return it.key == selectedKeys[0]
                                        })[0]
                                        this.setState({
                                            curitem
                                        })
                                        departmember({ id: selectedKeys[0] }).then(res => {
                                            if (res.code == 0) {
                                                this.setState({
                                                    dataSource: res.data.list,
                                                })
                                            }
                                        })
                                    }}
                                    onExpand={this.onExpand}
                                    expandedKeys={expandedKeys}
                                    autoExpandParent={autoExpandParent}
                                >
                                    {loop(treeData ? treeData : [])}
                                </Tree>
                            </div>
                        </div>
                    </Col>
                    <Col {...cols} style={{ padding: "0 20px" }}>
                        <p className="title" style={{ marginTop: 20, marginBottom: 20 }}>{this.state.curitem ? this.state.curitem.title : ""}部门下人员列表</p>
                        <AutoTable
                            dataSource={this.state.dataSource}
                            columns={[
                                {
                                    title: '姓名',
                                    dataIndex: 'name',
                                    key: 'name',
                                },
                                {
                                    title: '性别',
                                    dataIndex: 'sex',
                                    key: 'sex',
                                    search: false
                                },
                                {
                                    title: '手机号',
                                    dataIndex: 'phone',
                                    key: 'phone',
                                    search: false
                                },
                                {
                                    title: '查看详情',
                                    valueType: "option",
                                    render: (_, record) => {
                                        return <a>查看详情</a>
                                    }
                                },
                            ]}
                            withCard={false}
                        ></AutoTable>


                    </Col>
                </Row>

            </Card>
        );
    }
}

export default Department




